import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from logger import log
import os
import sys

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
        base_path = sys._MEIPASS
    else:
        base_path = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(base_path, relative_path)

VERSION = open(resource_path("version.m3u")).read().strip()

class RequestHandler(BaseHTTPRequestHandler):
    def _add_cors_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', '*')

    def do_GET(self):
        if self.path.startswith('/info'):
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self._add_cors_headers()
            self.end_headers()
            response = {
                "version": VERSION,
                "status": "idle"  # Or determine the actual status
            }
            self.wfile.write(json.dumps(response).encode('utf-8'))
        elif self.path.startswith('/'):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self._add_cors_headers()
            self.end_headers()
            self.wfile.write(b"<html><head><title>Version</title></head>")
            self.wfile.write(b"<body><p>Version: " + VERSION.encode('utf-8') + b"</p>")
            self.wfile.write(b"</body></html>")
        else:
            self.send_error(404)

    def do_OPTIONS(self):
        self.send_response(204)
        self._add_cors_headers()
        self.end_headers()

def run_server(port=8080):
    server_address = ('0.0.0.0', port)
    httpd = HTTPServer(server_address, RequestHandler)
    log.info(f"Starting http server on port {port}")
    httpd.serve_forever()

if __name__ == "__main__":
    run_server(8080)